package com.hue.springbootmybatis.plugins;

import com.hue.springbootmybatis.plugins.annotation.Tuomin;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.sql.Statement;
import java.util.List;
import java.util.function.Function;

/**
 * @Author: 姚凤桥
 * @Date: 2022/5/26 8:22
 * @Description: 加密插件
 */
@Component
@Intercepts(@Signature(type = ResultSetHandler.class, method = "handleResultSets", args = Statement.class))
public class TuominPlugins implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        List<Object> proceed = (List<Object>) invocation.proceed();
        proceed.forEach(this::tuomin);
        return proceed;
    }

    /**
     * 脱敏
     *
     * @param object
     */
    private void tuomin(Object object) {
        Class<?> aClass = object.getClass();
        Field[] fields = aClass.getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(Tuomin.class) && field.getType() == String.class) {
                Tuomin tuomin = field.getAnnotation(Tuomin.class);
                //获取脱敏策略
                Function<String, String> strategy = tuomin.strategy().getStrategy();
                try {
                    //将数据脱敏
                    field.setAccessible(true);
                    String apply = strategy.apply((String) field.get(object));
                    //将数据设置回原来的对象
                    field.set(object, apply);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
